package com.yztc.camerademo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import java.io.File;

/**
 * 演示拍照
 */
public class MainActivity extends AppCompatActivity {
    private ImageView iv;
    private String imagePath= Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).getAbsolutePath()+File.separator
            +"img.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv= (ImageView) findViewById(R.id.iv_show);
    }
    /*
    点击拍照按钮执行操作
     */
    public void camera(View view){
        Intent intent=new Intent();
        //拍照的action
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //指定拍摄的照片存储的路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imagePath)));
        startActivityForResult(intent,1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1 && resultCode== Activity.RESULT_OK){
            Bitmap bitmap= BitmapFactory.decodeFile(Uri.fromFile
                    (new File(imagePath)).getPath());
            if(bitmap!=null){
                iv.setImageBitmap(bitmap);
            }else{
                iv.setImageResource(R.mipmap.ic_launcher);
            }
        }
    }
}











